package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> user(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code:{}",code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
            SMSUtils.sendMessage("瑞吉外卖","SMS_273740803",phone,code);

            //生成的验证码保存到redis中
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            //session.setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map, HttpSession session){
        //获取登录验证码和手机号
        String phone = map.get("phone");
        String code = map.get("code");
        //获取session中密码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        //String codeInSession = (String) session.getAttribute(phone);
        //判断验证码是否一致
        if (code!=null && code.equals(codeInSession)){
            //登录成功,判断是否是新用户
            LambdaQueryWrapper<User> ulqw = new LambdaQueryWrapper<>();
            ulqw.eq(User::getPhone,phone);
            User user = userService.getOne(ulqw);
            if (user==null){
                //是新用户,保存
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将用户储存到session域
            session.setAttribute("user",user.getId());
            //删除验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        //验证码不同
        return  R.error("验证码有误,登录失败");
    }
}

